package com.action.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.action.ioc.component.AppComponent;
import com.action.ioc.component.ChildViewComponent;
import com.action.ioc.module.ChildModule;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.base.app_core.App;
import com.base.app_core.ui.WebActivity;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.Preferences;
import com.xinglai.yun.R;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.smtt.sdk.WebView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Set;


@Route(path = AppConstants.ROUTEURI.SHARE)
public class ShareActivity extends WebActivity {

    private Bitmap b;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_share;
    }

    @Override
    protected void setupComponent() {
        super.setupComponent();
        ((ChildViewComponent) ((AppComponent) App.getApp().getAppComponent()).plus(new ChildModule(this))).inject(this);
    }

    @Override
    protected void initData() {
        super.initData();
        App.getApp().regToWx();
    }

    @Override
    protected boolean shouldOverrideUrlLoading(WebView view, String url) {
        Uri uri = Uri.parse(url);
        // 如果url的协议 = 预先约定的 js 协议
        // 就解析往下解析参数
        if (uri.getScheme().equals("js")) {
            // 如果 authority  = 预先约定协议里的 webview，即代表都符合约定的协议
            // 所以拦截url,下面JS开始调用Android需要的方法
            if (uri.getAuthority().equals("webview")) {
                //  步骤3：
                // 执行JS所需要调用的逻辑
                System.out.println("js调用了Android的方法");
                // 可以在协议上带有参数并传递到Android上
                HashMap<String, String> params = new HashMap<>();
                Set<String> collection = uri.getQueryParameterNames();
            }
            return true;
        }
        return super.shouldOverrideUrlLoading(view, url);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    }

    @Override
    protected void initView() {
        super.initView();
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW,
                    Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }

        LinearLayout layout = (LinearLayout) findViewById(R.id.btnShare);
        if (null != layout) {
            //TODO 20180806 产生内存泄漏
            layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    try {
                        Bitmap bitmap = saveImage(webContent);
                        if (bitmap == null) {
                            return;
                        }

                        UMImage image = new UMImage(ShareActivity.this, bitmap);//本地文件
                        image.setThumb(new UMImage(ShareActivity.this, bitmap));

                        new ShareAction(ShareActivity.this)
                                .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                                .withText("hello")//分享内容
                                .withMedia(image)
                                .setCallback(new UMShareListener() {
                                    @Override
                                    public void onStart(SHARE_MEDIA share_media) {

                                    }

                                    @Override
                                    public void onResult(SHARE_MEDIA share_media) {
                                        recycleBitMap();
                                    }

                                    @Override
                                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                        Toast.makeText(ShareActivity.this, "失                                            败" + throwable.getMessage(), Toast.LENGTH_LONG).show();
                                        recycleBitMap();
                                    }

                                    @Override
                                    public void onCancel(SHARE_MEDIA share_media) {
                                        recycleBitMap();
                                    }
                                })//回调监听器
                                .open();

                    } catch (Exception e) {
                        CrashReport.postCatchedException(e);
                        e.printStackTrace();
                    }
                }
            });
        }
        setToolBar("分享好友");

        String percent = Preferences.getDefault().getString(AppConstants.SP.SHARE_SCALE_PERCENT, "5%");
        TextView shareHint = (TextView) findViewById(R.id.share_hint);
        try {
            if (shareHint != null) {
                shareHint.setText("邀请下线拆开红包奖励：" + new BigDecimal(percent).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString() + "%奖励");
            }
        } catch (NumberFormatException e) {
            if (shareHint != null) {
                shareHint.setText("邀请下线拆开红包奖励" + "5%" + "奖励");
            }
            e.printStackTrace();
        }
    }

    private void recycleBitMap() {
        if (b != null) {
            b.recycle();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    public Bitmap saveImage(WebView webView) {
        Picture picture = webView.capturePicture();
        if (b == null) {
            b = Bitmap.createBitmap(
                    picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
        }
        Canvas c = new Canvas(b);
        picture.draw(c);
        return b;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (App.getApp().iwxapi != null) {
//            App.getApp().iwxapi.detach();
//        }
    }

    @Override
    protected String getUrl() {
        return AppConstants.SERVER_URL + "index/share";
    }
}
